package com.cardone.common.util;

import com.cardone.common.security.DesTextEncryptor;
import lombok.Setter;
import org.jasypt.util.text.BasicTextEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;
import org.jasypt.util.text.TextEncryptor;

/**
 * Created by Administrator on 2014/12/26.
 */
public class TextEncryptorUtils {
    @Setter
    private static String passwordPrefix = "c1";

    public static String encrypt(String password, String encryptMessage) {
        return encrypt(null, password, encryptMessage);
    }

    public static String decrypt(String password, String decryptMessage) {
        return decrypt(null, password, decryptMessage);
    }

    public static String encrypt(String algorithm, String password, String encryptMessage) {
        return newTextEncryptor(algorithm, password).encrypt(encryptMessage);
    }

    public static String decrypt(String algorithm, String password, String decryptMessage) {
        return newTextEncryptor(algorithm, password).decrypt(decryptMessage);
    }

    private static TextEncryptor newTextEncryptor(String algorithm, String password) {
        if ("DES".equals(algorithm)) {
            DesTextEncryptor desTextEncryptor = new DesTextEncryptor();

            desTextEncryptor.setPassword(passwordPrefix + password);

            return desTextEncryptor;
        } else if ("PBEWithMD5AndTripleDES".equals(algorithm)) {
            StrongTextEncryptor strongTextEncryptor = new StrongTextEncryptor();

            strongTextEncryptor.setPassword(passwordPrefix + password);

            return strongTextEncryptor;
        } else {
            BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();

            basicTextEncryptor.setPassword(passwordPrefix + password);

            return basicTextEncryptor;
        }
    }

    public static void main(final String[] args) throws Exception {
        final String str = TextEncryptorUtils.encrypt("DES", "test", "sdfsdfsf");
        System.out.println(str);
        final String dstr = TextEncryptorUtils.decrypt("DES", "test", str);
        System.out.println(dstr);
    }
}
